<?php
/**
 * 星级&排名（文件）
 * (model)
 */
namespace App\Models\Operation\Crawl;

use App\Models\Basics\SysCountry;
use Illuminate\Database\Eloquent\Model;
class ReviewsFile extends Model
{
    protected $table = 'operation_crawl_reviews_file';

    protected $guarded = [];

    public function country(){
        return $this->belongsTo(SysCountry::class, 'country_id');
    }

    const FILE_NAME_DIR = 'reviews';

    const FILE_DIR = 'app'.DIRECTORY_SEPARATOR.'operation'.DIRECTORY_SEPARATOR.'crawl'.DIRECTORY_SEPARATOR.self::FILE_NAME_DIR;

    public static function getFile($date,$countryId){
        $fileDir = self::fileDir();
        $fileName = self::fileName($date,$countryId);
        $filePath = storage_path($fileDir).DIRECTORY_SEPARATOR.$fileName;
        $fileDir = dirname($filePath);
        if(!is_dir($fileDir)){
            mkdir($fileDir,0777,true);
            chmod($fileDir, 0777);
        }
        return $filePath;
    }

    public static function fileDir(){
        return self::FILE_DIR;
    }

    public static function fileName($date,$countryId){
        return date('Ymd',strtotime($date)).DIRECTORY_SEPARATOR.$countryId.'.csv';
    }

    public static function storeFile($date,$countryId){
        if(self::isExist($date,$countryId) == 0){
            return self::query()->create([
                'date' => $date,
                'country_id' => $countryId,
            ]);
        }
        return true;
    }

    public static function isExist($date,$countryId){
        return self::query()
            ->where('date',$date)
            ->where('country_id',$countryId)
            ->count();
    }
}
